<?php namespace App\Admin\Access\User\Criterias;

use Auth;
use App\Core\Repository\Criteria;
use App\Core\Repository\Repository;
use App\Admin\Access\Role\Repository as RoleRepository;

class HasPermission extends Criteria{

    public function apply(Repository $repository){
        parent::apply($repository);
        $user = Auth::user();
        if($user->isAdmin()){
            return ;
        }
		$roles = with(new RoleRepository())->getMyRoles();
		$roleIds = [];
		foreach ($roles as $role){
			$roleIds[] = $role->role_id;
		}
        $self = $this;
		return $this->query->where(function ($query) use($roleIds, $self){
            $query->whereNull($self->formatField($self->model, 'role_id'))
                ->orWhere($self->formatField($self->model, 'role_id'), '=', '');
            if($roleIds){
                $query->orWhereIn($self->formatField($self->model, 'role_id'), $roleIds);
            }
		});
    }
}